package com.csot.ry.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.common.annotation.Log;
import com.csot.common.constant.HttpStatus;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.entity.SysDictData;
import com.csot.common.core.domain.entity.SysUser;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.DictUtils;
import com.csot.common.utils.SecurityUtils;
import com.csot.common.utils.poi.ExcelUtil;
import com.csot.model.TotalSegment;
import com.csot.ry.domain.TTotalSegment;
import com.csot.ry.util.CacheKitUtil;
import com.csot.service.CoarseIdleIpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 空闲地址Controller
 *
 * @author LS
 * @date 2022-05-29
 */
@RestController
@RequestMapping("/ipmanagement/coarseidleip")
public class TCoarseIdleIpController extends BaseController {

    @Autowired
    private CoarseIdleIpService coarseipService;

    /**
     * 导出数据稽核列表
     */
    @Log(title = "粗粒度空闲", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{type}/**")
    public void export(HttpServletResponse response, TTotalSegment tTotalSegment, @PathVariable("type") String type) {
        //获取登入用户身份
        SysUser user = SecurityUtils.getLoginUser().getUser();
        long d = user.getDeptId();
        //如果是地市，只获取一次
        //如果是省，查询条件有地市，只获取一次
        //如果是省，获取14次
        List<TTotalSegment> dataList = new ArrayList<>();
        tTotalSegment.setIpType(type.toLowerCase());
        Long deptid = SecurityUtils.getLoginUser().getUser().getDept().getParentId();
        String city = CacheKitUtil.ip_dept.get(deptid + "");
        if (d != 100) {//100为省用户
            dataList = getCityDataByCity(tTotalSegment, city);
        } else {
            if (null != tTotalSegment.getIpCity()) {
                dataList = getCityDataByCity(tTotalSegment, tTotalSegment.getIpCity());
            } else {
                dataList = getAllData(tTotalSegment);
            }
        }
        dataList.stream().forEach(t -> {
            t.setIpType(CacheKitUtil.ip_type.get(t.getIpType()));
            t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
            t.setIpStatus(CacheKitUtil.ip_status.get(t.getIpStatus()));
        });

        ExcelUtil<TTotalSegment> util = new ExcelUtil<TTotalSegment>(TTotalSegment.class);
        util.exportExcel(response, dataList, "粗粒度空闲数据");
    }

    /**
     * 查询全量详细地址列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:idleip:list')")
    @GetMapping("/list/{type}/**")
    public TableDataInfo list(TTotalSegment tTotalSegment, @PathVariable("type") String type) {
        startPage();
        //获取登入用户身份
        SysUser user = SecurityUtils.getLoginUser().getUser();
        long d = user.getDeptId();
        //如果是地市，只获取一次
        //如果是省，查询条件有地市，只获取一次
        //如果是省，获取14次
        List<TTotalSegment> dataList = new ArrayList<>();
        tTotalSegment.setIpType(type.toLowerCase());
        Long deptid = SecurityUtils.getLoginUser().getUser().getDept().getParentId();
        String city = CacheKitUtil.ip_dept.get(deptid + "");
        if (d != 100) {//100为省用户
            dataList = getCityDataByCity(tTotalSegment, city);
        } else {
            if (null != tTotalSegment.getIpCity()) {
                dataList = getCityDataByCity(tTotalSegment, tTotalSegment.getIpCity());
            } else {
                dataList = getAllData(tTotalSegment);
            }
        }
        return getDataTable(dataList);
    }

    private List<TTotalSegment> getAllData(TTotalSegment tTotalSegment) {

        List<SysDictData> sysDictDataList = DictUtils.getDictCache("ip_city");
        List<TTotalSegment> dataList = new ArrayList<>();
        for (SysDictData sysDictData : sysDictDataList) {
            tTotalSegment.setIpCity(sysDictData.getDictValue());
            List<TTotalSegment> dataList_temp = getCityDataByCity(tTotalSegment, sysDictData.getDictValue());
            dataList.addAll(dataList_temp);
        }

        return dataList;
    }

    private List<TTotalSegment> getCityDataByCity(TTotalSegment tTotalSegment, String city) {
        List<TotalSegment> cacheList = coarseipService.handleByCity(tTotalSegment.getIpType(), city);
        // 查询
        List<TTotalSegment> dataList = cacheList.stream().map(m -> {
            TTotalSegment t = new TTotalSegment();
            BeanUtils.copyProperties(m, t);
            return t;
        }).collect(Collectors.toList());

        if (Objects.nonNull(tTotalSegment)) {
            dataList = dataList.stream().filter(f -> {
                long i = 0L;
                long end = 0L;
                String itCity = "";
                String ipType = "";
                String ipUser = "";
                if (StrUtil.isNotEmpty(tTotalSegment.getIpStart())) {
                    i = NetUtil.ipv4ToLong(tTotalSegment.getIpStart());
                }
                if (StrUtil.isNotEmpty(tTotalSegment.getIpEnd())) {
                    end = NetUtil.ipv4ToLong(tTotalSegment.getIpEnd());
                }
                if (StrUtil.isNotEmpty(tTotalSegment.getIpCity())) {
                    itCity = tTotalSegment.getIpCity();
                }
                if (StrUtil.isNotEmpty(tTotalSegment.getIpType())) {
                    ipType = tTotalSegment.getIpType();
                }

                if ((i > 0 ? (i <= f.getIpEndI()) : true)
                        && (end > 0 ? (end >= f.getIpStartI()) : true)
                        && (StrUtil.isNotEmpty(itCity) ? (f.getIpCity().equals(itCity)) : true)
                        && (StrUtil.isNotEmpty(ipType) ? (f.getIpType().equals(ipType)) : true)
                ) {
                    return true;
                }
//				if (f.getIpStartI() <= i && f.getIpEndI() <= i)
//					return true;
                return false;
            }).collect(Collectors.toList());
        }
        return dataList;
    }
    // 分页

    @Override
    protected TableDataInfo getDataTable(List<?> list) {
        PageUtil.setFirstPageNo(1);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        Page<Object> page = PageHelper.getLocalPage();
        int[] ps = PageUtil.transToStartEnd(page.getPageNum(), page.getPageSize());
        if (CollUtil.isEmpty(list)) {
            rspData.setRows(list);
            rspData.setTotal(new PageInfo(new ArrayList<>()).getTotal());
        } else {
            rspData.setRows(CollUtil.sub(list, ps[0], ps[1]));
            rspData.setTotal(list.size());
        }

        return rspData;
    }

}
